<template>
  <div class="role-manage">
    <el-card>
      <div class="search-bar">
        <el-input v-model="search" placeholder="搜索角色名" style="width: 200px;" @keyup.enter="fetchRoles" clearable />
        <el-button type="primary" style="margin-left: 8px;" @click="fetchRoles">查询</el-button>
        <el-button type="primary" @click="openAddDialog" style="float:right;">新增角色</el-button>
      </div>
      <el-table :data="roleList" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="角色名称" />
        <el-table-column prop="description" label="描述" />
        <el-table-column label="操作" width="260">
          <template #default="scope">
            <el-button size="mini" @click="openEditDialog(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            <el-button size="mini" type="success" @click="openMenuDialog(scope.row)">分配菜单</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 16px; text-align: right;"
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="pageSize"
        :current-page="page"
        @current-change="handlePageChange"
      />
    </el-card>

    <!-- 新增/编辑角色弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 分配菜单弹窗 -->
    <el-dialog title="分配菜单" :visible.sync="menuDialogVisible">
      <el-tree
        :data="menuTree"
        show-checkbox
        node-key="id"
        ref="menuTreeRef"
        :default-checked-keys="checkedMenuIds"
        :props="{ label: 'name', children: 'childMenu' }"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="menuDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSetMenus">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getRoleList, addRole, updateRole, deleteRole, getRoleMenus, setRoleMenus } from '@/api/role'
import { getMenuList } from '@/api/menu'

export default {
  name: 'RoleManage',
  data() {
    return {
      roleList: [],
      total: 0,
      page: 1,
      pageSize: 10,
      search: '',
      dialogVisible: false,
      dialogTitle: '新增角色',
      dialogType: 'add',
      form: { id: null, name: '', description: '' },
      rules: {
        name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
      },
      menuDialogVisible: false,
      menuTree: [],
      checkedMenuIds: [],
      currentRoleId: null
    }
  },
  methods: {
    async fetchRoles() {
      const params = { page: this.page, pageSize: this.pageSize, search: this.search }
      const res = await getRoleList(params)
      this.roleList = res.data.records
      this.total = res.data.total
    },
    handlePageChange(val) {
      this.page = val
      this.fetchRoles()
    },
    openAddDialog() {
      this.dialogType = 'add'
      this.dialogTitle = '新增角色'
      this.form = { id: null, name: '', description: '' }
      this.dialogVisible = true
    },
    openEditDialog(row) {
      this.dialogType = 'edit'
      this.dialogTitle = '编辑角色'
      this.form = { ...row }
      this.dialogVisible = true
    },
    async handleSubmit() {
      this.$refs.formRef.validate(async valid => {
        if (!valid) return
        if (this.dialogType === 'add') {
          await addRole(this.form)
        } else {
          await updateRole(this.form)
        }
        this.dialogVisible = false
        this.fetchRoles()
      })
    },
    async handleDelete(row) {
      this.$confirm('确定要删除该角色吗？', '提示', { type: 'warning' })
        .then(async () => {
          await deleteRole(row.id)
          this.fetchRoles()
        })
        .catch(() => {})
    },
    /**
     * 分配菜单
     * @param row 角色
     */
    async openMenuDialog(row) {
      this.currentRoleId = row.id
      const menuRes = await getMenuList()
      this.menuTree = menuRes.data
      const roleMenuRes = await getRoleMenus(row.id)
      console.log(roleMenuRes)
      this.checkedMenuIds = roleMenuRes.data.map(ele => ele.menuId) || []
      console.log(this.checkedMenuIds)
      this.menuDialogVisible = true
      this.$nextTick(() => {
        this.$refs.menuTreeRef.setCheckedKeys(this.checkedMenuIds)
      })
    },
    async handleSetMenus() {
      const checkedKeys = this.$refs.menuTreeRef.getCheckedKeys()
      await setRoleMenus(this.currentRoleId, checkedKeys)
      this.menuDialogVisible = false
      this.$message.success('分配成功')
    }
  },
  mounted() {
    this.fetchRoles()
  }
}
</script>

<style scoped>
.role-manage {
  padding: 24px;
}
.search-bar {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style> 